;
// 预报端须
(function() {
    var main = {
        router: {
            getBoxPlotData: CafeJS.CXT + 'analysis/getBoxPlotData.do',
            getLatestTime: CafeJS.CXT+'/analysis/getModelLatestTime.do',
            exportChart:  CafeJS.CXT + 'common/exportChart.do',
        },
        rstData: {},
        singleEle: [
            { 'ele': 'TP6H', 'title': '降水量', 'unit': 'mm' },
            { 'ele': 'TMP2M', 'title': '2m温度', 'unit': '℃' },
            { 'ele': 'EDA10M', 'title': '10m风', 'unit': 'm/s' },
            { 'ele': 'RH2M', 'title': '2m相对湿度', 'unit': '%' },
            { 'ele': 'SNOW6H', 'title': '降雪', 'unit': 'mm' }
        ],
        init: function() {
        	$.IDate(".date-panel2", {
				query: function query() {
				}
			});
            this.getLatestTime();
            for (var i = 0; i < this.singleEle.length; i++) {
                this.createContainer($('.welkin_pro_container'), this.singleEle[i].ele);
            }
            this.bindEvt();
            this.buildLastTime();

        },
        // 获取最新起报时间
        getLatestTime: function() {
        	var that = this;
        	var param = {
        		pcode: 'TMP2M-ECJH',
        		area: 'AFSH',
                height: 0,
                threshold: 'MEDIAN'
        	};
        	$.ajax({
        		url: this.router.getLatestTime,
        		type: 'GET',
        		dataType: 'json',
        		async: false,
        		data: param
        	}).done(function(res){
        		if (res.success && res.params.data) {
        			var latestTime = dateUtil.convertStringToDate7(res.params.data,'yyyy-MM-dd hh:mm');
        			$("#queryDate").IDatePicker().setVal(latestTime);
        		}
        	})
        },
        // 初始化最近起报时间
        buildLastTime: function() {
            var baseDate = $("#queryDate").IDatePicker().getVal() + ":00";
            var newDate = new Date(baseDate);
            var liArr = [];
            for (var i = 0; i < 4; i++) {
                liArr.push(`<li class="${i == 0 ? 'active' : ''}" data-time="${newDate}">${newDate.format("ddhh")}</li>`);
                newDate.setHours(newDate.getHours() - 12);
            }
            $(".pnewtime-ct").empty().append(liArr.reverse().join(""));
            $(".pnewtime-ct").children().last().click();
        },
        createContainer: function(obj, ele_id) {
            // 创建容器
            var container = $('<div class="welkin_chart_container" ele="' + ele_id + '"></div>');
            var chart_container = $('<div class="welkin_chart"></div>');
            // 添加chart容器
            container.append(chart_container);
            container.append('<div class="slider_div_container"><div class="slider_div"></div></div>');
            // 添加按钮
            container.append('<div class="ec_btns_container">' +
                '<div class="ec_btn_item chart_btn_first icon-zhiding" flg="first"></div>' +
                '<div class="ec_btn_item icon-xiangshang" flg="prev"></div>' +
                '<div class="ec_btn_item icon-xiangxia" flg="next"></div>' +
                '<div class="ec_btn_item chart_btn_last icon-zhidi" flg="last"></div>' +
                '</div>');
            obj.append(container);
        },
        createChartData: function(data, len) {
            var xxdata = [];
            var times = [];
            var avg_val = [];
            var mid_val = [];
            if (!len) {
                len = data.length;
            }
            for (var j = 0; j < len; j++) {
                var d = data[j];
                var time = new Date(d.bjDatetime);
                xxdata.push([d.max_val, d.valninty_per, d.valseventy_per, d.mid_num, d.valtwenty_per, d.valten_per, d.min_val]);
                times.push(j);
                avg_val.push({ x: j, y: d.avg_val, time: time });
                mid_val.push({ x: j, y: d.mid_num, time: time });
            }
            return {
                xxdata: xxdata,
                xdata: times,
                avg: avg_val,
                mid: mid_val
            };
        },
        getCharDataLen: function(value) {
            var len = 8;
            if (value <= 72) {
                len = value / 3;
            } else {
                len = 72 / 3 + (value - 72) / 6;
            }
            return len;
        },
        doQuery: function() {
            var _this = this;
            var queryTime = $(".pnewtime-ct li.active").data('time');
            queryTime = new Date(queryTime).format('yyyyMMddhhmmss');
            var stationId = $('#pcity-single li.active').data('code');
            var param = {
                queryTime: queryTime,
                mode: 'ECJIHE',
                stationId: stationId
            };
            $.getJSON(_this.router.getBoxPlotData, param, function(result) {
                _this.iniSlider();
                if (!result.success) return;
                for (var i = 0; i < _this.singleEle.length; i++) {
                    var ele = _this.singleEle[i]['ele'];
                    _this.rstData[ele] = result.params.data[ele];
                    var len = _this.getCharDataLen($('.welkin_chart_container[ele=' + ele + '] .slider_div').slider("getValue"));
                    var param = _this.createChartData(result.params.data[ele], len);
                    param.text = _this.singleEle[i].title + '（' + _this.singleEle[i].unit + '）'
                    _this.createChart($('.welkin_chart_container[ele=' + ele + '] .welkin_chart'), param, _this.createSeries(param), result.params.data[ele]);
                }
            })
        },
        createSeries: function(param) {
            return [{
                name: 'Observations',
                data: param.xxdata,
                boxColors: ['#c34ef4', '#fdcb46', '#4f78f4', '#fd5151'],
                color: '#000',
                tooltip: {
                    headerFormat: '<em>Experiment No {point.key}</em><br/>'
                }
            }, {
                name: 'Control',
                color: '#00FFFF',
                type: 'spline',
                data: param.mid,
                marker: {
                    fillColor: '#00FFFF',
                    lineWidth: 1,
                    lineColor: '#00FFFF',
                    radius: 2
                },
                tooltip: {
                    pointFormat: 'Control: {point.y}'
                }
            }, {
                name: 'Mean',
                color: '#FE0100',
                type: 'spline',
                data: param.avg,
                marker: {
                    fillColor: '#FE0100',
                    lineWidth: 1,
                    lineColor: '#FE0100',
                    radius: 2
                },
                tooltip: {
                    pointFormat: 'Mean: {point.y}'
                }
            }];
        },
        createChart: function(obj, param, series, data) {
        	var that = this;
            obj.highcharts({
                rstData: data,
                chart: {
                    type: 'customboxplot'
                },
                lang: {
                    contextButtonTitle: ''
                },
                credits: {
                    enabled: false
                },
                title: {
                    text: param.text
                },
                tooltip: {
                    shared: true,
                    useHTML: true,
                    formatter: function() {
                        var t = new Date(this.points[1].point.time);
                        var title = "<small style='color: #294e81;font-weight: bold;'>" + t + "时 </small><br/>";
                        var key = this.points[0].key;
                        var datas = this.points[0].series.yData[key];
                        var names = ["最大值", "90%分位值", "75%分位值", "中位值", "平均值", "25%分位值", "10%分位值", "最小值"];
                        var index = 0;
                        for (var i = 0; i < names.length; i++) {
                            var yval = "";
                            if ("平均值" == names[i]) {
                                yval = this.points[2].y;
                            } else {
                                yval = datas[index];
                                index++;
                            }
                            title += "<div class='tooltip_text'>" + names[i] + "：" + yval + "</div>";
                        }
                        return title;
                    },
                    style: {
                        fontSize: '12px',
                        padding: '8px'
                    },
                    borderRadius: 10
                },
                exporting: {
                    enabled: true,
                    buttons: {
                        contextButton: {
                            text: "下载",
                            height: 50,
                            symbolX: 17,
                            symbolY: 13,
                            onclick: function() {
                                var obj = this;
                                var sindex = obj.title.textStr.indexOf("（");
                                var eindex = obj.title.textStr.indexOf("）");
                                var str = obj.title.textStr.substr(0, sindex) + obj.title.textStr.substr(eindex + 1)+'.png';
                                $("#filename").val(str);
                                $("#svgCode").val(obj.getSVG({
                                    chart: {
                                        width: obj.chartWidth,
                                        height: obj.chartHeight
                                    }
                                }));
                                $("#svgForm").attr('action', that.router.exportChart);
                                $("#svgForm").submit();
                            },
                            theme: {
                                fill: "#C7E1FF",
                                stroke: "#68A"
                            },
                            symbol: 'url(' + CafeCxtPath + '/business/analysis/common/css/images/download.png)'
                        }
                    }
                },
                legend: {
                    enabled: false
                },

                xAxis: {
                    categories: param.xdata,
                    labels: {
                        step: (param.xdata.length - param.xdata.length % 10) / 10,
                        style: {
                            color: '#386db4'
                        },
                        formatter: function() {
                            var t = new Date(this.chart.options.rstData[this.value].bjDatetime);
                            var d = t.getDate() > 9 ? t.getDate() : '0' + t.getDate();
                            var h = t.getHours() > 9 ? t.getHours() : '0' + t.getHours();
                            return d + '' + h;
                        }
                    }
                },

                yAxis: {
                    title: {
                        text: ""
                    }
                },
                series: series

            });
        },
        iniSlider: function() {
            var _this = this;
            $('.slider_div').slider({
                value: 72,
                showTip: false,
                step: 24,
                min: 24,
                max: 168,
                rule: ["024", "048", "072", "096", "120", "144", "168"],
                onChange: function(value, oldValue) {
                    var obj = $(this).parent().prev();
                    var param = _this.createChartData(_this.rstData[obj.parent().attr('ele')], _this.getCharDataLen(value))
                    $(this).parent().prev().highcharts().series[0].setData(param.xxdata);
                    $(this).parent().prev().highcharts().series[1].setData(param.mid);
                    $(this).parent().prev().highcharts().series[2].setData(param.avg);
                }
            });
        },
        bindEvt: function() {
            var that = this;
            // 最新起报时间
            $(".pnewtime-ct").on("click", 'li', function() {
                $(this).addClass("active").siblings().removeClass("active");
                var time = $(this).data('time');
                $("#queryDate").IDatePicker().setVal(time);
                that.doQuery();
            })
            // 站点切换单选
            $("#pcity-single").on("click", 'li', function() {
                $(this).addClass("active").siblings().removeClass("active");
                that.doQuery();
            })
            $('.date-panel2').off('click').on('click', '.btn-forward', function(e) { // 日期向前
                e.stopPropagation();
                $("#queryDate").IDatePicker().toForward();
            }).on('click', '.btn-backward', function(e) { // 日期向后
                e.stopPropagation();
                $("#queryDate").IDatePicker().toBackward();
            }).on('click', ".btn-search", function (e) { // 搜索
				e.stopPropagation();
				that.buildLastTime();
			}).on('click', ".btn-newest", function(e) { // 最新
                e.stopPropagation();
                $("#queryDate").IDatePicker().toNewest();
                that.buildLastTime();
            });

            $('.ec_btn_item').css("color", "");
            $('.ec_btn_item.chart_btn_first:first').css("color", "#ccc").next().css("color", "#ccc");
            $('.ec_btn_item.chart_btn_last:last').css("color", "#ccc").prev().css("color", "#ccc");
            // chart图按钮点击事件
            $('.welkin_pro_container').on('click', '.ec_btn_item', function() {
                var pObj = $(this).parents('.welkin_chart_container');
                switch ($(this).attr('flg')) {
                    case 'first':
                        if (pObj.prevAll('.welkin_chart_container:last').length > 0) {
                            pObj.prevAll('.welkin_chart_container:last').before(pObj);
                        }
                        break;
                    case 'prev':
                        if (pObj.prev().length > 0)
                            pObj.prev().before(pObj);
                        break;
                    case 'next':
                        if (pObj.next().length > 0)
                            pObj.next().after(pObj);
                        break;
                    case 'last':
                        if (pObj.nextAll('.welkin_chart_container:last').length > 0) {
                            pObj.nextAll('.welkin_chart_container:last').after(pObj);
                        }
                        break;
                }
                $('.ec_btn_item').css("color", "");
                $('.ec_btn_item.chart_btn_first:first').css("color", "#ccc").next().css("color", "#ccc");
                $('.ec_btn_item.chart_btn_last:last').css("color", "#ccc").prev().css("color", "#ccc");
            });
        }
    }
    main.init();
})()